// ClientProgramDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ClientProgram.h"
#include "ClientProgramDlg.h"
#include "IPAddr.h"
#include "Message.h"
#include <atlconv.h>
#include <atlbase.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CClientProgramDlg dialog




CClientProgramDlg::CClientProgramDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CClientProgramDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CClientProgramDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	/*DDX_IPAddress(pDX, IDC_MYIP, _myIP);*/
	DDX_IPAddress(pDX, IDC_SERVERIP, _serverIP);
	/*DDX_Control(pDX, IDC_MYIP, _myIPCtrl);*/
	DDX_Control(pDX, IDC_SERVERIP, _serverIPCtrl);
	DDX_Control(pDX, IDC_TXTCHAT, _myTextBox);
	DDX_Control(pDX, IDC_LSTUSER, _myUserList);
	DDX_Control(pDX, IDC_CHAT, _myChatBox);
	DDX_Control(pDX, IDC_USERNAME, _myUsername);
	DDX_Control(pDX, IDC_BTNCONNECT, _btnConnect);
	DDX_Control(pDX, IDC_BTNSEND, _btnSend);
}

BEGIN_MESSAGE_MAP(CClientProgramDlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BTNCONNECT, &CClientProgramDlg::OnClickedBTNConnect)
	ON_BN_CLICKED(IDC_BTNDISCONNECT, &CClientProgramDlg::OnClickedBTNDisconnect)
	ON_BN_CLICKED(IDC_BTNSEND, &CClientProgramDlg::OnClickedBTNSend)
END_MESSAGE_MAP()


// CClientProgramDlg message handlers

BOOL CClientProgramDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	GetDlgItem(IDC_BTNDISCONNECT)->EnableWindow(FALSE);
	GetDlgItem(IDC_BTNSEND)->EnableWindow(FALSE);
	GetDlgItem(IDC_TXTCHAT)->EnableWindow(FALSE);
	//_myIPCtrl.SetAddress(192,168,1,2);
	_serverIPCtrl.SetAddress(127,0,0,1);
	GetDlgItem(IDC_USERNAME)->SetFocus();
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CClientProgramDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CClientProgramDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



//My function
void CClientProgramDlg::OnClickedBTNConnect()
{
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,2), &wsaData);

	//SOCKET cSocket;
	_connectSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	
	//Lay username de tao message login
	USES_CONVERSION;
	CString textChat;
	_myUsername.GetWindowText(textChat);
	char* iUsername = new char [200];

	int sizeOfString = (textChat.GetLength() + 1);
	LPTSTR lpsz = new TCHAR[sizeOfString];
	_tcscpy_s(lpsz, sizeOfString, textChat);
	iUsername = T2A(lpsz);

	if (strcmp(iUsername,"") == 0)
	{
		MessageBox(_T("Username is blank. Type your username"),_T("Error"),MB_OK);
		return;
	}

	BYTE byteBuf[4];
	//MyIP
	/*myIPString = new char[15];
	
	_myIPCtrl.GetAddress(byteBuf[0],byteBuf[1],byteBuf[2],byteBuf[3]);
	CIPAddr myIPAddr (byteBuf[0],byteBuf[1],byteBuf[2],byteBuf[3]);
	myIPAddr.ToChar(myIPString);*/

	//Server IP
	serverIPString = new char[15];
	_serverIPCtrl.GetAddress(byteBuf[0],byteBuf[1],byteBuf[2],byteBuf[3]);
	CIPAddr serverIPAddr (byteBuf[0],byteBuf[1],byteBuf[2],byteBuf[3]);
	serverIPAddr.ToChar(serverIPString);

	//Init connect Socket
	sockaddr_in sAddr;
	sAddr.sin_family = AF_INET;
	sAddr.sin_port = htons(3000);
	sAddr.sin_addr.S_un.S_addr = inet_addr(serverIPString);

	int iConnectResult = connect(_connectSocket,(sockaddr*)&sAddr,sizeof(sAddr));
	if (iConnectResult !=0)
	{
		MessageBox(_T("Cannot connect to server"),_T("Error!!!"),MB_OK);
		return;
	}

	//Tao thread lang nghe thong diep tu server
	AfxBeginThread(RecieveThread,this);

	_username = new char [200];
	strcpy(_username,iUsername);

	//Gui message Login
	char* buf = new char[300];
	CMessage loginMes;
	loginMes.SetCode('1');
	loginMes.SetUser(iUsername);
	loginMes.SetMes("");

	loginMes.ToChar(buf);
	int len = strlen(buf);
	int i = send(_connectSocket,buf,len,0);
	delete buf;
	
}
void CClientProgramDlg::OnClickedBTNDisconnect()
{
	CMessage iMes;
	iMes.SetCode('2');
	iMes.SetUser(_username);
	iMes.SetMes("");

	char* buf = new char[300];
	iMes.ToChar(buf);
	send(_connectSocket,buf,strlen(buf),0);

	SetDlgItemText(IDC_STATE,_T("Disconnected"));
	GetDlgItem(IDC_BTNCONNECT)->EnableWindow(TRUE);
	GetDlgItem(IDC_BTNDISCONNECT)->EnableWindow(FALSE);
	GetDlgItem(IDC_BTNSEND)->EnableWindow(FALSE);
	GetDlgItem(IDC_TXTCHAT)->EnableWindow(FALSE);
	GetDlgItem(IDC_USERNAME)->EnableWindow(TRUE);
	GetDlgItem(IDC_SERVERIP)->EnableWindow(TRUE);

	_btnConnect.SetFocus();
	SetDefID(IDC_BTNCONNECT);

	_myUserList.ResetContent();
	_myChatBox.ResetContent();
}
void CClientProgramDlg::OnClickedBTNSend()
{
	USES_CONVERSION;
	CString textChat;
	_myTextBox.GetWindowText(textChat);
	char* textChar = new char [200];

	int sizeOfString = (textChat.GetLength() + 1);
	LPTSTR lpsz = new TCHAR[sizeOfString];
	_tcscpy_s(lpsz, sizeOfString, textChat);
	textChar = T2A(lpsz);
	
	if (strcmp(textChar,"") == 0)
	{
		return;
	}
	//--Tao message--//
	CMessage iMes;
	iMes.SetCode('3');
	iMes.SetUser(_username);
	iMes.SetMes(textChar);

	char* buf = new char[300];
	iMes.ToChar(buf);

	int i = send(_connectSocket,buf,strlen(buf),0);
	delete buf;
	//--Set textchat = ""--//
	_myTextBox.SetWindowText(_T(""));
}
void CClientProgramDlg::OnClose()
{
	if (_connectSocket != INVALID_SOCKET)
	{
		CMessage iMes;
		iMes.SetCode('2');
		iMes.SetUser(_username);
		iMes.SetMes("");

		char* buf = new char[300];
		iMes.ToChar(buf);
	
		send(_connectSocket,buf,strlen(buf),0);
	}
	OnCancel();
}
